<template>
	<view class="container">
		<!-- :covers="covers"  显示起点到终点的所有经纬度坐标点 -->
		<map class="map" :longitude="center.longitude" :latitude="center.latitude" id="map" :markers="markers"
			:polyline="polyline" :covers="covers"></map>
		<button class="playback-btn" :class="{ active: isPlayback }"
			@click="togglePlayback">{{ isPlayback ? '停止导航' : '开始导航' }}</button>

	</view>
</template>

<script>
	import QQMapWX from '../../common/qqmap-wx-jssdk.js'
	import {
		terminalCoordinate
	} from '../../api/work.js'
	const qqMapSDK = new QQMapWX({
		key: 'M5JBZ-XEZCJ-6SPFB-DH4E5-QFCS7-FCBTQ'
	})

	export default {
		data() {
			return {
				// 地图中心点
				center: {
					latitude: 43.586135,
					longitude: 87.458778
				}, // 地图中心点
				markers: [], // 路线规划起终点标记
				polyline: [], // 路线规划线段
				covers: [], // 轨迹回放点标记
				trackData: [], // 轨迹数据
				currentIndex: 0, // 当前回放点索引
				hasRoute: false, // 是否已规划路线
				followMode: true, // 是否开启跟随模式  true 跟随模式 
				isPlayback: false, // 是否正在进行轨迹回放
				timer: null, // 定时器
				rotate: 90
			}
		},
		onLoad(option) {
			//获取羊ID
			if (option.id) {
				terminalCoordinate(option.id).then(data => {
					let {
						data: {
							obj
						}
					} = data
					obj.map(item => {
						this.calculateRoute(item)
					})
				})
			} else {
				console.log('·····暂无目标ID·······');
			}

		},
		mounted() {
			//调用token
			this.getToken()
			console.log(this.covers, '····························阿斯顿发生');
		},
		methods: {
			// 获取语音播报token
			getToken() {
				let that = this
				uni.request({
					url: 'https://aip.baidubce.com/oauth/2.0/token',
					data: {
						grant_type: 'client_credentials',
						// 百度地图的API Key
						client_id: 'BkZEIkHYY6puRLViv9kQ75tV',
						// Secret Key
						client_secret: 'o3d3qXGpvv3tXjzx6VIPfhR4OXnd0hR4'
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
					},
					method: 'POST',
					success: res => {
						that.token = res.data.access_token
						console.log(that.token, '··········百度语音：token');
					}
				})
			},
			// 播放语音
			startAudio(text) {
				const innerAudioContext = uni.createInnerAudioContext();
				/*
				  创建一个 innerAudioContext对象 
				*/
				innerAudioContext.autoplay = true;
				let cuid = '8VsaICKXnLaU5k3RujExzJJZFPmvUAIq'
				let ctp = '3'
				let lan = 'zh'
				let aue = '3'
				let spd = '6'

				// 调用语音合成的API接口
				innerAudioContext.src =
					`http://tsn.baidu.com/text2audio?tex=${text}&
				tok=${'24.a69b14db018695987fc3b5a2f92961ab.2592000.1701174589.282335-41281873'}&cuid=${cuid}&
				ctp=${ctp}&lan=${lan}&aue=${aue}&spd=${spd}`

				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
			},
			// 调用路线
			toggleRoute() {
				if (this.hasRoute) {
					this.clearRoute()
				} else {
					this.calculateRoute()
				}
			},
			// 规划路线
			calculateRoute(obj) {
				console.log(obj);
				const _this = this //暂存this
				// 开始坐标点
				const startLocation = {
					latitude: 43.586135,
					longitude: 87.458778
				}
				// 终点
				const endLocation = {
					latitude: obj.latitude,
					longitude: obj.longitude,
				}
				// 绘制路线*
				qqMapSDK.direction({
					mode: 'bicycling',
					from: startLocation,
					to: endLocation,
					success: res => {
						console.log(res, '···········结果············');
						// 所有经纬度坐标
						const route = res.result.routes[0].polyline
						const steps = res.result.routes[0].steps //方向
						console.log(steps);
						// console.log(route,'············原数据所有经纬度··········');
						// // 前向差分解压 坐标解压（返回的点串坐标，通过前向差分进行压缩）
						let polyline = [];
						let list = []
						for (let i = 2; i < route.length; i++) {
							route[i] = Number(route[i - 2]) + Number(route[i]) / 1000000
							list.push(route[i])
						}
						for (let i = 0; i < list.length; i += 2) {
							polyline.push({
								latitude: list[i],
								longitude: list[i + 1],
							})
						}
						// 绘制markers
						const markers = [{
								id: 1,
								width: 40,
								height: 40,
								longitude: polyline[0].longitude,
								latitude: polyline[0].latitude,
								iconPath: '/static/start.png',
								rotate: 0,
								// 位置偏移量
								anchor: {
									x: 0.5,
									y: 0.5
								}
							},
							{
								id: 2,
								width: 40,
								height: 40,
								longitude: obj.longitude,
								latitude: obj.latitude,
								iconPath: 'https://img0.baidu.com/it/u=1467052035,1222001525&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1697562000&t=603feb359d0f99a34d7b66f1ddb4bd54'
							}
						]
						polyline[0].steps = steps[0].instruction
						polyline[20].steps = '即将' + steps[0].act_desc
						polyline[24].steps = steps[0].act_desc
						polyline[25].steps = '延当前道路继续' + steps[1].instruction + '然后' + steps[2].instruction
						polyline[45].steps = steps[2].act_desc
						polyline[47].steps = '延当前道路' + steps[3].instruction
						// polyline[6].steps = '即将' + steps[1].act_desc
						// polyline[7].steps = steps[1].act_desc
						// polyline[8].steps = "延当前道路" + steps[2].instruction
						// polyline[19].steps = '即将' + steps[2].act_desc
						// polyline[20].steps = steps[2].act_desc
						// polyline[21].steps = steps[3].instruction + '然后' + steps[4].instruction
						// polyline[33].steps = '即将' + steps[4].act_desc
						// polyline[34].steps = steps[4].act_desc
						// polyline[35].steps = "沿当前道路" + steps[5].instruction
						// polyline[40].steps = '即将' + steps[5].act_desc
						// polyline[41].steps = steps[5].act_desc
						// polyline[44].steps = steps[6].act_desc
						// polyline[45].steps = "沿当前道路" + steps[7].instruction
						// 41 
						console.log(polyline, '··················处理后的结果');
						_this.markers = markers
						_this.polyline = [{
							points: polyline,
							color: '#00aaffdd',
							width: 10,
						}]
						_this.hasRoute = true
					},
					fail: error => {
						console.log(error, '············路线规划出错咯··········');
					}

				})
			},
			// 切换回放状态
			togglePlayback() {
				if (this.isPlayback) {
					// 停止回放
					this.stopPlayback()
				} else {
					// 回放
					this.startPlayback()
				}
			},
			// 开始轨迹回放
			startPlayback() {
				if (this.isPlayback) {
					return
				}
				this.isPlayback = true
				this.currentIndex = 0
				// 开启语音播报
				this.startAudio('开始为您导航')
				// 初始化轨迹回放点
				this.initPlaybackCovers()
				// 开始回放定时器
				this.timer = setInterval(() => {
					this.playNextPoint()
				}, 3000)
			},
			// 停止轨迹回放
			stopPlayback() {
				clearInterval(this.timer)
				this.isPlayback = false
				this.currentIndex = 1
				// this.covers = []
			},
			// 初始化轨迹回放点
			initPlaybackCovers() {
				// 显示起点到终点之间生成的所有经纬度位置信息
				this.covers = this.polyline[0].points.map((point, index) => {
					return {
						id: new Date(),
						longitude: point.longitude,
						latitude: point.latitude,
						width: 20,
						height: 20
					}
				})
			},
			// 更新轨迹回放点位置
			updatePlaybackCovers(longitude, latitude) {
				this.covers[this.currentIndex].longitude = longitude
				this.covers[this.currentIndex].latitude = latitude
				// 开始的markers点移动
				this.markers[0].latitude = latitude
				this.markers[0].longitude = longitude
			},
			// 播放下一个轨迹点
			playNextPoint() {
				if (this.currentIndex < this.polyline[0].points.length) {
					const point = this.polyline[0].points[this.currentIndex]
					// console.log(point,'·················标记点········');
					if (point['steps']) {
						this.startAudio(point['steps'])
					}
					// 更新地图中心点和回放点标记
					// this.center.longitude = point.longitude
					// this.center.latitude = point.latitude
					// 传入下一个坐标
					this.updatePlaybackCovers(point.longitude, point.latitude)
					// 跟随模式
					if (this.followMode) {
						// 切换当前中心点位置
						uni.createMapContext('map', this).moveToLocation({
							longitude: point.longitude,
							latitude: point.latitude
						})
					}
					console.log(this.currentIndex, '···········我是索引');
					// 坐标索引++
					this.currentIndex++
				} else {
					this.stopPlayback() // 回放结束
				}
			},
			// 地图平移时关闭跟随模式
			onRegionChange(e) {
				if (e.type === 'begin') {
					this.followMode = false
				}
			},

		}
	}
</script>

<style>
	.container {
		height: 100vh;
	}

	.map {
		width: 100%;
		height: 90%;
	}

	.route-btn,
	.follow-btn,
	.reset-btn {
		position: absolute;
		padding: 10px;
		font-size: 16px;
		background-color: #fff;
		border-radius: 8px;
	}

	.route-btn {
		top: 20px;
		left: 20px;
	}

	.playback-btn {
		height: 10%;
		line-height: 61px;
		padding-bottom: 10px;
	}

	.follow-btn {
		bottom: 20px;
		right: 20px;
	}

	.reset-btn {
		bottom: 20px;
		left: 20px;
	}

	.active {
		background-color: #3f81c1;
		color: #fff;
	}
</style>